package com.yishusmt.wechatapi.wechatdev.serviceImpl;

import com.yishusmt.wechatapi.wechatdev.constant.*;
import com.yishusmt.wechatapi.wechatdev.dto.base.Item;
import com.yishusmt.wechatapi.wechatdev.entity.HostUrlEntity;
import com.yishusmt.wechatapi.wechatdev.entity.TextMessageEntity;
import com.yishusmt.wechatapi.wechatdev.entity.WechatMemebrEntity;
import com.yishusmt.wechatapi.wechatdev.mapper.HostUrlEntityMapper;
import com.yishusmt.wechatapi.wechatdev.mapper.TextMessageInfoMapper;
import com.yishusmt.wechatapi.wechatdev.service.*;
import com.yishusmt.wechatapi.wechatdev.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;


/**
 * 微信接收消息
 *
 * @author zhangyi
 * @date 2018/8/27 15:05
 */
@Service
@Slf4j
public class WechatReceiveServiceImpl implements WechatReceiveService {


    @Autowired
    private MessageHandleService messageHandleService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private AsyncTaskService asyncTaskService;

    @Autowired
    private TextMessageInfoMapper textMessageInfoMapper;

    @Autowired
    private LocalMessageUtil localMessageUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HostUrlEntityMapper hostUrlEntityMapper;

    @Autowired
    private MessageHandlerUtil messageHandlerUtil;

    /**
     * 接收消息，回复内容
     * 将方法异步化
     *
     * @return
     */
    @Override
    public String receiveAndSend() throws IOException, URISyntaxException {
        //发送消息
        String message = null;
        //获取上下文的Http请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //接收实体
        Map<String, String> receving = WeChatXmlUtil.xmlToObj(request);
        //用户身份实体
        WechatMemebrEntity wechatMemebrEntity = new WechatMemebrEntity();

        String toUserName = receving.get("ToUserName");
        String fromUserName = receving.get("FromUserName");
        String createTime = receving.get("CreateTime");
        String msgType = receving.get("MsgType");
        String content = receving.get("Content");
        String msgId = receving.get("MsgId");
        //事件类型
        String event = receving.get("Event");
        //菜单跳转
        String key = receving.get("EventKey");
        //发送实体
        Map<String, String> send = new HashMap<>();
        send.put("ToUserName", fromUserName);
        send.put("FromUserName", toUserName);
        send.put("CreateTime", String.valueOf(Long.parseLong(createTime)));
        send.put("MsgType", MessageConstant.RESP_MESSAGE_TYPE_TEXT);
        send.put("MsgId", msgId);
        send.put("Event", event);
        wechatMemebrEntity.setCreateTime(DateUtil.getLocalDate());
        wechatMemebrEntity.setCreateTime(DateUtil.getLocalDate());
        wechatMemebrEntity.setOpenid(fromUserName);

        //失败信息随机返回
        List<TextMessageEntity> textMessages = null;
        StringBuffer failMessage = new StringBuffer();

//        事件发送
        if (EventConstant.EVENT.equals(msgType)) {
            switch (event) {
                case EventConstant.SUBSCRIBE:
                    List<Item> items = new ArrayList<>();
                    Object o = articleService.welArticle(ItemConstant.WELCOME_ITEM);
                    if (o instanceof Item) {
                        items.add((Item) o);
                        //图文消息
                        message = MessageUtil.sendImgAndText(send, items);
                    } else if (o instanceof String) {
                        //纯文本消息
                        message = MessageUtil.sendText(send, o.toString());
                    }
                    asyncTaskService.saveUser(wechatMemebrEntity);
                    break;
                case EventConstant.UN_SUBSCRIBE:
                    //取消关注
                    //保存取消关注的用户信息
                    asyncTaskService.saveUser(wechatMemebrEntity);
                    break;
                case EventConstant.VIEW:
                    //view拿到的是连接地址不是key值
                    System.out.println("请求地址:" + key);
                    //根据地址判断用户点击行为
                    System.out.println(fromUserName);
                    break;
                case EventConstant.CLICK:
                    log.info("事件::{} key::{}",EventConstant.CLICK,key);
                    HostUrlEntity hostUrlEntity = hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.HOST_ORDER_ID);
                    //主机
                    String host = hostUrlEntity.getHost();
                    //拼接的连接
                    String req = null;
                    //处理连接
                    if(StringUtils.contains(key,OrderConstant.QUICK)){
                        //下单
                        System.out.println("获取到"+fromUserName);
                        //拼接快速下单连接
                        req = host+"/"+hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.X_URL).getHost()+"?openId="+fromUserName;
                        //中转站发送文章体
                        Item item = new Item();
                        List<Item> list = new ArrayList<>();
                        item.setPicUrl(hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.X_IMG_URL).getHost());
                        item.setUrl(req);
                        item.setDescription(hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.X_DESC).getHost());
                        item.setTitle(hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.X_TITLE).getHost());
                        list.add(item);
                        message = MessageUtil.sendImgAndText(send,list);

                    }else if(StringUtils.contains(key,OrderConstant.INFO)){
                        //查询订单
                        System.out.println("获取到"+fromUserName);
                        //拼接查询订单连接
                        req = host+hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.C_URL).getHost()+"?openId="+fromUserName;
                        Item item = new Item();
                        List<Item> list = new ArrayList<>();
                        item.setPicUrl(hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.C_IMG_URL).getHost());
                        item.setUrl(req);
                        item.setDescription(hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.C_DESC).getHost());
                        item.setTitle(hostUrlEntityMapper.selectByPrimaryKey(OrderConstant.C_TITLE).getHost());
                        list.add(item);
                        message = MessageUtil.sendImgAndText(send,list);
                    }
                    break;
                case EventConstant.LOCATION:
                    log.info("用户的地理位置上报");
                    break;
                case EventConstant.VERIFY_EXPIRED:
                    log.info("认证过期失效... ...");
                    break;
                default:
                    break;
            }
        } else {
//            输入消息类型
            switch (msgType) {
                case MessageConstant.RESP_MESSAGE_TYPE_TEXT:
                    //验证码处理
                    boolean isCache = localMessageUtil.checkCode(content, fromUserName);
                    if(isCache){
                        //验证正确
                        String s = MD5Util.encryptString(fromUserName);
                        redisUtil.set(RedisConstant.USER_TOKEN+s
                                ,AESUtil.encryptString(fromUserName,s)
                                ,60*60*24*30L);
                        return  MessageUtil.sendText(send,"验证成功!");
                    }
                    //本地业务查询
                    String localStr = messageHandleService.userLocalMessageHandle(content,fromUserName);
                    boolean present = Optional.ofNullable(localStr).isPresent();
                    if (!present) {
                        //判断是否需要第三方来执行
                        String returnStr = messageHandleService.userMessageHandle(content);
                        //判断用户输入的信息是否可以处理
                        if (content.equals(returnStr)) {
                            String failmsg = failHandle(textMessageInfoMapper.selectFailInfo(ItemConstant.FAIL_ITEM));
                            message = MessageUtil.sendText(send, failmsg);
                        } else {
                            //信息分类展示
                            message = messageHandlerUtil.MessageScheduling(send,content);
                        }
                    } else {
                        message = MessageUtil.sendText(send, localStr);
                    }
                    break;
                case MessageConstant.REQ_MESSAGE_TYPE_IMAGE:
                    //纯图片回复
                    break;
                case MessageConstant.REQ_MESSAGE_TYPE_VOICE:
                    //音频回复
                    break;
                default:
                    String failmsg = failHandle(textMessageInfoMapper.selectFailInfo(ItemConstant.FAIL_ITEM));
                    message = MessageUtil.sendText(send, failmsg);
                    break;
            }
        }
        return message;
    }

    /**
     * 失败提示消息处理
     *
     * @param texts
     * @return
     */
    private String failHandle(List<TextMessageEntity> texts) {
        StringBuffer failMessage = new StringBuffer();
        texts = textMessageInfoMapper.selectFailInfo(ItemConstant.FAIL_ITEM);
        Integer randSize = (int) Math.floor(Math.random() * texts.size());
        failMessage.append(texts.get(randSize).getTextDesc());
        return failMessage.toString();
    }
}
